<?php
declare(strict_types=1);
namespace SixShop\WechatPay\Model;

use app\model\UserModel;
use SixShop\Payment\Enum\NumberBizEnum;
use think\db\Query;
use think\Model;
use SixShop\WechatPay\Enum\TransferBillStatusEnum;
use think\model\relation\BelongsTo;

class WechatpayTransferBillModel extends Model
{
    protected function getOptions(): array
    {
        return [
            'name' => 'wechatpay_transfer_bill',
            'type' => [
                'state' => TransferBillStatusEnum::class,
            ],
            'insert' => ['out_bill_no'],
            'readonly' => ['user_id', 'mch_id', 'out_bill_no', 'appid', 'transfer_amount', 'fee', 'openid', 'user_name'],
        ];
    }

    public function getStateTextAttr($value, $data)
    {
        return $data['state']->toString();
    }

    public function searchStateAttr(Query $query, $value)
    {
        $value = TransferBillStatusEnum::tryFrom($value);
        if ($value) {
            $query->where('state', $value);
        }
    }

    public function searchOutBillNoAttr(Query $query, $value)
    {
        if ($value) {
            $query->where('out_bill_no', $value);
        }
    }

    protected function setOutBillNoAttr($value, $data): string
    {
        return generate_number(NumberBizEnum::WITHDRAWAL);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(UserModel::class, 'user_id');
    }
}